<?php

namespace app\admin\controller\history;

use app\admin\model\Course;
use app\common\controller\Backend;
use think\Exception;
use think\exception\DbException;
use think\response\Json;

/**
 * 历年真题目录
 *
 * @icon fa fa-circle-o
 */
class Date extends Backend
{

    /**
     * Date模型对象
     * @var \app\admin\model\history\Date
     */
    protected $model = null;

    /**
     * Course模型对象
     * @var Course
     */
    protected $courseModel = null;

    /**
     * 是否是关联查询
     */
    protected $relationSearch = true;

    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = 'name';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\history\Date;
        $this->courseModel = new Course();
    }

    /**
     * 列表
     * @return string|Json
     * @throws Exception
     * @throws DbException
     */
    public function index()
    {
        // 设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        // 请求参数
        $param = $this->request->param();

        // 提取参数
        $course_id = $param['course_id'] ?? 0;

        // 提交查询
        if ($this->request->isAjax()) {
            // 如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $otherWhere = [];
            if ($course_id) {
                $otherWhere['course_id'] = $course_id;
            }
            $list = $this->model
                ->with('course')
                ->where($where)
                ->where($otherWhere)
                ->order($sort, $order)
                ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }

        // 查看课程信息
        $courseName = '';
        if ($course_id) {
            $courseName = $this->courseModel->where(['id' => $course_id])->value('name', '');
        }

        // 注入变量
        $this->view->assign('course_id', $course_id);
        $this->view->assign('courseName', $courseName);
        return $this->view->fetch();
    }

    /**
     * 添加
     * @return string
     */
    public function add()
    {
        // 请求参数
        $param = $this->request->param();

        // 提取参数
        $course_id = $param['course_id'] ?? 0;
        $this->view->assign('course_id', $course_id);
        return parent::add();
    }

}
